package com._9xcloud.leaverequest.web.controller;

import com._9xcloud.leaverequest.exception.ClientLogicalErrorException;
import com._9xcloud.leaverequest.exception.InvalidPasswordException;
import com._9xcloud.leaverequest.exception.NotFoundException;
import com._9xcloud.leaverequest.web.transfer.Failure;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * Created by hyq on 2015/5/25.
 */
@ControllerAdvice
public class ExceptionController {
    @ExceptionHandler(AuthenticationException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public Failure handleAuthenticationException(AuthenticationException ex) {
        return new Failure(HttpStatus.UNAUTHORIZED.value(), ex.getLocalizedMessage());
    }

    @ExceptionHandler(NotFoundException.class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    @ResponseBody
    public Failure handleNotFoundException(NotFoundException ex) {
        return new Failure(HttpStatus.NOT_FOUND.value(), ex.getLocalizedMessage());
    }

    @ExceptionHandler(InvalidPasswordException.class)
    @ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
    @ResponseBody
    public Failure handleInvalidPasswordException(InvalidPasswordException ex) {
        return new Failure(HttpStatus.NOT_ACCEPTABLE.value(), ex.getLocalizedMessage());
    }

    @ExceptionHandler(ClientLogicalErrorException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Failure handleClientLogicalErrorException(ClientLogicalErrorException ex) {
        return new Failure(HttpStatus.BAD_REQUEST.value(), ex.getLocalizedMessage());
    }

    @ExceptionHandler(TypeMismatchException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Failure handleTypeMismatchException(TypeMismatchException ex) {
        return new Failure(HttpStatus.BAD_REQUEST.value(), ex.getLocalizedMessage());
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public Failure handleMissingServletRequestParameterException(MissingServletRequestParameterException ex) {
        return new Failure(HttpStatus.BAD_REQUEST.value(), ex.getLocalizedMessage());
    }
}
